import org.junit.Test;
import  com.google.gson.Gson;
import java.util.*;

import static javafx.scene.input.KeyCode.P;

public class JsonTest {
    @Test
    //javaBean 和json互转
    public void text1() {

        Person person;
        person = new Person(1, "毛不易");
        //创建gson对象实例
        Gson gson = new Gson();
        //toJson方法可以把Java对象转换成为json字符串
        String personJsonString = gson.toJson(person);
        System.out.println(personJsonString);
        //fromJson把json字符串转换回Java对象
        //第一个参数是json字符串
        //第二个参数是转换回去的Java对象类型
        Person person1 = gson.fromJson(personJsonString, Person.class);
        System.out.println(person1);
    }

    public void text2(){
        List<Person> personList = new ArrayList<>();
        personList.add(new Person(1, "毛不易"));
        Gson gson = new Gson();

        //把list转换为json字符串
        String personListJsontring = gson.toJson(personList);
        System.out.println(personListJsontring);
        List<Person>list=gson.fromJson(personListJsontring,new PersonListType().getType());
        System.out.println(list);
        Person person=list.get(0);
        System.out.println(person);
    }

    public void text3(){
        Map<Integer, Person> personMap = new HashMap<>();
        personMap.put(1, new Person(1, "123456"));

        Gson gson = new Gson();
        //把map集合转换为json字符串
        String personMapJsonString = gson.toJson(personMap);
        System.out.println(personMapJsonString);
        Map<Integer, Person>  personMap1 = gson.fromJson(personMapJsonString,new PersonMapType().getType());
        System.out.println(personMap1);
        Person p=personMap1.get(1);
        System.out.println(P);
    }
}